package com.leige.utils.tool;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class AnnotationUtils {
	
	
	public static  class Entry<T,R>{
		private T annotation;
		private R root;
		public T getAnnotation() {
			return annotation;
		}
		public R getRoot() {
			return root;
		}
		public Entry(R root,T annotation) {
			this.annotation = annotation;
			this.root = root;
		}
		public boolean equals(Entry<T,R> obj) {
			// TODO Auto-generated method stub
			return this.getRoot().equals(obj.getRoot())&&this.getAnnotation().equals(obj.getAnnotation());
		}
	}
	
	public static  <T extends Annotation > List<Entry<T, Class<?>>> getAnnotation(Class<?> o,Class<T> t ){
		return getAnnotation(o, t,new ArrayList<Entry<T,Class<?>>>());
	}
	public static <T extends Annotation,R> List<Entry<T,R>> getAnnotation(Class<?> o,Class<T> t,List<Entry<T,R>> list){
		Entry<T,R> k = new Entry(o,o.getAnnotation(t));
		for (Entry<T, R> k_ : list) {
			if(k_.equals(k))return list;
		}
		if(k.getAnnotation()!=null)
			list.add(k);
		
		for (Method method : o.getMethods()) {
			 k = new Entry(method,method.getAnnotation(t));
			 if(k.getAnnotation()!=null)
				 list.add(k);
		}
		for (Class<?> interfaces : o.getInterfaces())
			if(interfaces!=null&&interfaces!=Object.class)
				getAnnotation(interfaces, t,list);
		Class<?> superclass = o.getSuperclass();
		if(superclass!=null&&superclass!=Object.class)
			getAnnotation(superclass, t,list);
	  return list;
	}
}

